<template>
  <div v-loading="loading" class="formBox" style="position: relative">
    <el-row class="rowBox">
      <el-col :span="24">
        <iframe id="iframes" ref="iframe" v-resize="{ heightCalculationMethod: 'lowestElement', checkOrigin: false }" width="100%" frameborder="0" :src="formUrl" />
      </el-col>
      <el-col :span="24">
        <el-form v-if="formBase.fileUpload === 'Y'">
          <!-- 附件列表 -->
          <FileTable ref="fileTable" :list.sync="fileList" :data-type="formBase.uniqueKey" :business-type="this.$route.query.dealType" :select-business-data="this.$route.query.dealType === undefined" :btn-show="!otherBtnHide" />
        </el-form>
      </el-col>
    </el-row>
    <div v-if="footerShow" slot="footer" class="dialog-footer" style="text-align: center;position: absolute;right: 20px;">
      <template v-if="formBase.enableProcess === 'Y'">
        <FormBtn ref="formBtn" :bus-data="rowData" :has-permi="formBase.permissions" :btn-hide="btnHide" :cancel-func="cancel" />
      </template>
      <template v-else>
        <save-btn v-if="btnShow" :cancel-func="cancel" :has-permi="formBase.permissions" :cancel-show="openLocation === undefined" />
      </template>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { config } from '@/utils'
import {
  getByFormIdAndDataId,
  getFormBase,
  saveFormData
} from '@/api/dev/form/base/formBase'

export default {
  props: {
    formIdProp: {
      type: String,
      default: undefined
    },
    parameter: {
      type: Object,
      default: undefined
    }
  },
  data() {
    return {
      otherBtnHide: false,
      btnShow: false,
      formUrl: null,
      visible: false,
      loading: false,
      formId: this.$route.query.formId,
      dataId: undefined,
      height: 300,
      iframeHeight: '100%',
      formBase: {},
      rowData: {},
      fileList: [],
      btnHide: false,
      iframeWin: {},
      // 打开页面的位置，如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
      openLocation: undefined,
      footerShow: true
    }
  },
  computed: {
    token() {
      return 'Bearer ' + getToken()
    },
    backUrl() {
      return config.baseURL
    }
  },
  created() {},
  activated() {},
  mounted() {
    this.$bus.$emit('async_done')
    window.addEventListener('scroll', this.handleScroll, true)
    window.loading = this.loading
    window.getByFormId = (id) => {
      this.calculateHeight()
      return getByFormIdAndDataId({ formId: this.formId, dataId: id })
    }
    window.getLanguage = (key) => {
      return this.$t(key)
    }
    window.token = getToken()
    window.baseUrl = process.env.VUE_APP_BASE_API
    window.currentLoginUserId = this.$store.state.user.userId
    window.userTree = this.$store.state.user.userTree
    window.initProperty = {
      deal_status: this.$route.query.dealStatus,
      deal_type: this.$route.query.dealType
    }
  },
  methods: {
    handleScroll() {
      var iwindow = document.getElementById('iframes').contentWindow
      var idoc = iwindow.document
      idoc.body.style.height = 'unset'
    },
    init(data) {
      this.visible = true
      if (this.parameter && this.parameter.formId) {
        this.formId = this.parameter.formId
      }
      if (data && data.formId) {
        this.formId = data.formId
      }
      getFormBase(this.formId).then((res) => {
        this.formBase = res.data
        this.btnShow = true
        this.loading = false
      })
      if (data) {
        this.footerShow = !data.wfNodeId
      }
      if (data && data.id) {
        this.formUrl = process.env.BASE_URL + 'magicalcoder/magicalcoder.html?formId=' + this.formId + '&dataId=' + data.id
        this.dataId = data.id
        window.dataId = this.dataId
        this.getByFormId(data.id)
      } else {
        if (data && data.fileList !== undefined) {
          this.fileList = data.fileList
        }
        window.dataId = undefined
        this.dataId = undefined
        this.formUrl = process.env.BASE_URL + 'magicalcoder/magicalcoder.html?formId=' + this.formId
        if (window.genForm?.resetFields !== undefined) {
          window.genForm.resetFields()
        }
        if (this.$refs.iframe.contentWindow?.initProperty !== undefined) {
          this.$refs.iframe.contentWindow.initProperty()
        }
      }
    },
    getByFormId(id) {
      this.loading = true
      getByFormIdAndDataId({ formId: this.formId, dataId: id }).then((res) => {
        this.rowData = res.data
        this.fileList = res.data.fileList
        this.loading = false
      })
    },
    // submitCheck() {
    //   // 外部vue向iframe内部传数据
    //   this.iframeWin.postMessage({
    //     cmd: 'submitCheck',
    //     params: {}
    //   }, '*')
    // },
    // receiveMessage(event) {
    //   const data = event.data
    //   switch (data.cmd) {
    //     case 'returnCheck':
    //       break
    //   }
    //
    //   // 根据上面制定的结构来解析iframe内部发回来的数据
    //   // const valid = event.valid
    //   // console.log(valid)
    // },
    submitForm(type) {
      this.loading = true
      const data = {
        formId: this.formId,
        dataId: this.dataId,
        data: this.$refs.iframe.contentWindow.getData(),
        insertFuncEvent: this.formBase.insertFuncEvent,
        fileList: this.fileList
      }
      if (this.formBase.joinField && this.formBase.joinField !== '') {
        data.data.sourceId = this.$route.query[this.formBase.joinField]
      }
      // 校验附件
      var flagValidate = true
      if (this.formBase.fileUpload === 'Y') {
        if (this.fileList !== undefined && this.fileList !== null && this.fileList.length > 0) {
          this.fileList.forEach(item => {
            if (item.name === undefined || item.name === '' || item.name === null) {
              flagValidate = false
            }
          })
        }
      }
      if (!flagValidate) {
        this.msgError(this.$t('请完善附件列表信息'))
      }
      // this.submitCheck()
      return new Promise((resolve, reject) => {
        window.genForm.validate((valid) => {
          if (valid && flagValidate) {
            saveFormData(data).then((res) => {
              if (res.code === 200) {
                this.dataId = res.data
                if (type === 'process') {
                  // 启动流程
                  this.startProcess(this.dataId)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  if (this.$parent.$parent.reset) {
                    this.$parent.$parent.cancel()
                    // 关闭form页面
                    this.$parent.$parent.reset()
                  }
                }
                this.loading = false
                resolve(res.data)
              } else {
                this.msgError(res.msg)
                reject()
              }
              // this.formOpenLoading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.loading = false
            var document = this.$refs.iframe.contentWindow.document
            this.locationError(document)
          }
        })
      })
    },
    cancel() {
      if (this.$parent.$parent.formOpen) {
        this.$parent.$parent.formOpen = false
      }
    },
    calcPageHeight(doc) {
      var cHeight = Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
      var sHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight)
      var height = Math.max(cHeight, sHeight)
      return height
    },
    // 启动流程
    startProcess: function(dataId) {
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.formBase.name
      // 业务表名
      processData.dataTable = this.formBase.uniqueKey
      // 业务ID
      processData.dataId = dataId
      processData.formId = this.formId
      // 业务表单地址
      processData.formPath = '@/views/dev/form/base/form'

      // 业务表单打印地址
      processData.viewPath = ''

      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.formBase.uniqueKey
      this.startProcessByMenu(processData, () => {
        // this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.$parent.$parent.reset()
      })
    },
    // 计算高度
    calculateHeight() {
        var height = $('#iframes').contents().find('form').height()
        if (height !== undefined) {
          $('#iframes').height(height)
        }
    }
  }
}
</script>

<style scoped>
</style>
